//
//  MGBaseFlowLayout.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/7/26.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGBaseFlowLayout.h"
#import <YYBBaseViews/YYBShadowView.h>

@interface MGBaseFlowLayout ()
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;
@property (nonatomic, strong) YYBShadowView *placeholderView;

@property (nonatomic) CGPoint dragOffset;
@property (nonatomic, strong) NSIndexPath *beginIndexPath;

@property (nonatomic) CGFloat cellHeight;
@property (nonatomic) CGFloat cellOffset;
@property (nonatomic) CGFloat contentBottomInset;

@end

@implementation MGBaseFlowLayout

- (instancetype)initWithCellHeight:(CGFloat)cellHeight cellOffset:(CGFloat)cellOffset contentBottomInset:(CGFloat)contentBottomInset
{
    self = [super init];
    if (!self) return nil;
    
    _cellHeight = cellHeight;
    _cellOffset = cellOffset;
    _contentBottomInset = contentBottomInset;
    
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    
    _attributes = [NSMutableArray new];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (NSInteger index = 0; index < count; index ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        [_attributes addObject:attributes];
    }
    
    if (!_longPress) {
        _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        _longPress.minimumPressDuration = 0.3f;

        [self.collectionView addGestureRecognizer:_longPress];
    }
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)longPress
{
    CGPoint point = [longPress locationInView:longPress.view];
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self handleLongPressBeginAtPoint:point];
    } else if (longPress.state == UIGestureRecognizerStateChanged) {
        if (_beginIndexPath) {
            [self handleLongPressUpdateAtPoint:point];
        }
    } else if (longPress.state == UIGestureRecognizerStateEnded) {
        if (_beginIndexPath) {
            [self handleLongPressRemoveAtPoint:point];
        }
    }
}

- (void)handleLongPressBeginAtPoint:(CGPoint)point
{
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    if (!indexPath) return;

    YYBCollectionViewCell *cell = (YYBCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    UIView *snapView = [cell.wrapperView snapshotViewAfterScreenUpdates:YES];
    snapView.backgroundColor = APP_COLOR_BACKGROUND;

    _placeholderView = [[YYBShadowView alloc] init];
    [_placeholderView.shadowView setLayerShadow:[UIColor colorWithHexValue:0x000000 alpha:0.2] offset:CGSizeZero radius:6];
    [_placeholderView.contentView cornerRadius:8];
    [_placeholderView.contentView addSubview:snapView];
    
    _beginIndexPath = indexPath;
    cell.hidden = YES;

    UIView *targetView = self.collectionView.superview.superview;
    targetView.userInteractionEnabled = NO;

    CGRect snapRect = [targetView convertRect:snapView.frame fromView:cell.contentView];
    snapRect.origin.x = 10;
    _placeholderView.frame = snapRect;
    snapView.frame = _placeholderView.bounds;
    
    _dragOffset = CGPointMake(_placeholderView.center.x - point.x, _placeholderView.center.y - point.y);
    [targetView addSubview:_placeholderView];
}

- (void)handleLongPressUpdateAtPoint:(CGPoint)point
{
    CGPoint center = CGPointMake(point.x + self.dragOffset.x, point.y + self.dragOffset.y);
    _placeholderView.center = center;
    
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    if (indexPath && indexPath.row != self.beginIndexPath.row) {
        [self updateLayoutWithIndexPath:self.beginIndexPath targetIndexPath:indexPath];
    }
}

- (void)handleLongPressRemoveAtPoint:(CGPoint)point
{
    [_placeholderView removeFromSuperview];
    
    // tableView
    UIView *targetView = self.collectionView.superview.superview;
    targetView.userInteractionEnabled = YES;
    
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:_beginIndexPath];
    cell.hidden = NO;
    
    if (self.arrangeSuccBlock) {
        self.arrangeSuccBlock();
    }
}

- (void)updateLayoutWithIndexPath:(NSIndexPath *)indexPath targetIndexPath:(NSIndexPath *)targetIndexPath
{
    id dataModel = [self.dataModels objectAtIndex:indexPath.row];
    [self.dataModels removeObjectAtIndex:indexPath.row];
    [self.dataModels insertObject:dataModel atIndex:targetIndexPath.row];
    
    [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:targetIndexPath];
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    _beginIndexPath = targetIndexPath;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attributes.frame = CGRectMake(0, indexPath.row * (_cellHeight + _cellOffset) , kScreenWidth, _cellHeight);
    return attributes;
}

- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _attributes;
}

- (CGSize)collectionViewContentSize
{
    return CGSizeMake(kScreenWidth, (self.dataModels.count + 1) * (_cellHeight + _cellOffset) + _contentBottomInset);
}

@end
